package br.com.foxline.atlasmobile.request;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.widget.Toast;
import br.com.foxline.atlasmobile.R;
import br.com.foxline.atlasmobile.dao.DneDao;
import br.com.foxline.atlasmobile.entities.Dne;
import br.com.foxline.atlasmobile.util.UtilConnection;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class ImportDne extends AsyncTask<String, String, Boolean> {

	private DneDao dneDao;
	private Context context;
	private ProgressDialog dialog;
	private SharedPreferences prefs;
	private String server;
	private String portNumber;

	public ImportDne(Context context) {
		super();
		this.context = context;
		dneDao = new DneDao(this.context);
		prefs = this.context.getSharedPreferences(
				UtilConnection.APP_SHARED_PREFS, 0);
		server = prefs.getString(UtilConnection.SERVER,
				UtilConnection.SERVER_DEFAULT);
		portNumber = prefs.getString(UtilConnection.PORT_NUMBER,
				UtilConnection.PORT_NUMBER_DEFAULT);
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		this.dialog = new ProgressDialog(this.context);
		this.dialog.setCancelable(true);
		this.dialog.setTitle("Atualizando Base de Endereços");
		this.dialog.setMessage("Atualizando");
		this.dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		this.dialog.setProgress(0);
		this.dialog.setMax(100);
		this.dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
						dialog.dismiss();
					}
				});
		this.dialog.show();
	}

	@Override
	protected Boolean doInBackground(String... arg0) {
		SynchronousHttpConnection httpConnection = new SynchronousHttpConnection(
				server, portNumber);
		StringBuilder response = new StringBuilder();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(
					"dd/MM/yyyy HH:mm:ss.SSS");
			response.append(httpConnection.post(UtilConnection.URL_SYNC_DNE, ""
					+ sdf.format(dneDao.getLastDateUpdate())));

			Gson gson = new GsonBuilder().setDateFormat(
					"dd/MM/yyyy HH:mm:ss.SSS").create();
			List<Dne> l = (List<Dne>) gson.fromJson(response.toString(),
					new TypeToken<List<Dne>>() {
					}.getType());

			if (l.isEmpty()) {
				return false;
			} else {
				int cont = 0;
				this.dialog.setMax(l.size());

				for (Dne dne : l) {
					cont++;
					this.dialog.setProgress(cont);
					onProgressUpdate("Enviando " + cont + "/" + l.size());
					if (dneDao.exist(dne.getId())) {
						dneDao.update(dne);
					} else {
						dneDao.create(dne);
					}
				}
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return true;
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
		if (result){
			this.dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setText(
					"Concluir !");
		}else{
			Toast.makeText(context, "Não há atualizações", Toast.LENGTH_SHORT).show();
			this.dialog.cancel();
			this.dialog.dismiss();
		}

	}
}
